package com.ruoyi.common.gscUtil;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * https://chat.deepseek.com/a/chat/s/fe6b38c5-5bee-4ad8-b027-c7ff767cb286
 * 轻松实现创建人、创建时间、更新人、更新时间等字段的自动填充
 */
@Component
public class MetaObjectHandlerCustomer implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createBy", String.class, getCurrentUsername()); // 创建人
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); // 创建时间
        this.strictInsertFill(metaObject, "updateBy", String.class, getCurrentUsername()); // 更新人
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date()); // 更新时间
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateBy", String.class, getCurrentUsername()); // 更新人
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date()); // 更新时间
    }

    private String getCurrentUsername() {
        LoginUser loginUser = getLoginUser();
        // 这里实现获取当前用户名的逻辑，例如从 SecurityContext 中获取
        return loginUser.getUser().getNickName(); // 示例
    }
}